
#include "InvoiceItemDelegate.h"
#include "InvoiceItemModel.h"

using namespace ecocity;

InvoiceItemDelegate::InvoiceItemDelegate( QObject *parent )
        : QItemDelegate( parent )
{
}

//---------------------------------------------------------------

void
InvoiceItemDelegate::paint( QPainter *painter,
                              const QStyleOptionViewItem &option,
                              const QModelIndex &index ) const
{
    QStyleOptionViewItem my_option = option;
    my_option.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;

    QString text;

    switch ( index.column( ) )
    {
    case InvoiceItemsModel::ITEM_UNTAXED_PRICE_UNIT_OR_KILO:
    {
        float price = index.model()->data( index, Qt::DisplayRole ).toFloat( );
        text = QString::number( price, 'f', 2 );

        const QAbstractItemModel* model = index.model( );

        const QModelIndex index_price_type =
                model->index( index.row( ), InvoiceItemsModel::ITEM_PRICE_TYPE );

        const QString price_type_str = index_price_type.data( ).toString( );

        Product::PRICE_TYPE price_type =
                Product::to_price_type( price_type_str );

        switch ( price_type )
        {
        case Product::PER_KILO:
        {
            text.append( QString::fromUtf8( " €/Kilo" ) );
            break;
        }
        case Product::PER_UNIT:
        {
            text.append( QString::fromUtf8( " €/Uni." ) );
            break;
        }
        default:
            break;
        }
        break;
    }
    case InvoiceItemsModel::ITEM_TAX_RATE:
    {
        int price = index.model()->data( index, Qt::DisplayRole ).toInt();
        text = QString::number( price );
        text.append( QString::fromUtf8( " %" ) );
        break;
    }
    case InvoiceItemsModel::ITEM_DISCOUNT_RATE:
    {
        int price = index.model()->data( index, Qt::DisplayRole ).toFloat( );
        text = QString::number( price, 'f', 2  );
        text.append( QString::fromUtf8( " %" ) );
        break;
    }
    case InvoiceItemsModel::ITEM_TAXES:
    case InvoiceItemsModel::ITEM_DISCOUNT_EUR:
    case InvoiceItemsModel::ITEM_UNTAXED_PRICE_WITHOUT_DISCOUNT:
    case InvoiceItemsModel::ITEM_TOTAL_UNTAXED_PRICE:
    case InvoiceItemsModel::ITEM_TOTAL_PRICE:
    {
        float price = index.model()->data( index, Qt::DisplayRole ).toFloat( );
        text = QString::number( price, 'f', 2 );
        text.append( QString::fromUtf8(" €" ) );
        break;
    }
    case InvoiceItemsModel::ITEM_WEIGHT:
    {
        float weight = index.model()->data( index, Qt::DisplayRole ).toFloat( );
        text = QString::number( weight, 'f', 3 );
        text.append( " kg" );
        break;
    }
    default:
        QItemDelegate::paint( painter, option, index );
        return; // return is fine here
    }

    drawDisplay( painter, my_option, my_option.rect, text );
    drawFocus( painter, my_option, my_option.rect );
}


